package com.baidumap.administrator.happystudy.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.dialog.loadingDialog.LoadingDialogUtil;
import com.ab.http.OnMessageResponse;
import com.ab.util.AbStrUtil;
import com.ab.util.ToastUtil;
import com.ab.view.dialog.StyledDialog;
import com.ab.view.dialog.bottomsheet.BottomSheetBean;
import com.ab.view.dialog.interfaces.MyItemDialogListener;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseActivity;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.model.CarDel;
import com.baidumap.administrator.happystudy.model.Subject;
import com.baidumap.administrator.happystudy.module.photo.activity.AlbumActivity;
import com.baidumap.administrator.happystudy.module.photo.activity.GalleryActivity;
import com.baidumap.administrator.happystudy.module.photo.util.Bimp;
import com.baidumap.administrator.happystudy.module.photo.util.FileUtils;
import com.baidumap.administrator.happystudy.module.photo.util.ImageItem;
import com.baidumap.administrator.happystudy.module.photo.util.PublicWay;
import com.baidumap.administrator.happystudy.module.photo.util.Res;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by C on 2017/3/26.
 */
public class NewQuestionActivity extends AppBaseActivity implements View.OnClickListener, OnMessageResponse {

    @Bind(R.id.et_title)
    EditText etTitle;
    @Bind(R.id.tv_content)
    EditText tvContent;
    @Bind(R.id.tv_xuan_ze_lei_xing)
    TextView tvXuanZeLeiXing;
    private PopupWindow mPopupWindow;
    private LinearLayout mLlXuanze;
    private LinearLayout mLlBeforeChoose;
    private RelativeLayout mRlAfterChoose;
    private PopupWindow mPhotoPopup;
    private ImageView mIvPicture;

    private String mTitle, mContent, mLeiXing;

    private GridView noScrollgridview;
    private GridAdapter adapter;
    private View parentView; 
    private PopupWindow pop = null;
    private LinearLayout ll_popup;
    public static Bitmap bimap;
    private List<String> imagesPath = new ArrayList<>();
    private List<BottomSheetBean> kemuList = new ArrayList<>();
    private List<String> kemuIdList = new ArrayList<>();

    private String mKemuId;

    private SimpleDraweeView dvWelcome;
    DraweeController draweeController;
    @Override
    public int bindLayout() {
        return R.layout.activity_new_question;
    }
 
    @Override
    public void initView(View view) {
        super.initView(view);
        mLlXuanze = (LinearLayout) view.findViewById(R.id.ll_xuanze);
        mLlBeforeChoose = (LinearLayout) view.findViewById(R.id.ll_before_choose);
        mRlAfterChoose = (RelativeLayout) view.findViewById(R.id.rl_after_choose);
        mIvPicture = (ImageView) view.findViewById(R.id.iv_picture);
        mIvPicture.setOnClickListener(this);
        ImageView image = (ImageView) view.findViewById(R.id.image);
        image.setOnClickListener(this);

        mLlXuanze.setOnClickListener(this);
        initPopWindow();
        initPhotoPopup();

        Res.init(this);
        bimap = BitmapFactory.decodeResource(
                getResources(),
                R.mipmap.icon_addpic_unfocused);
        PublicWay.activityList.add(this);
        parentView = getLayoutInflater().inflate(R.layout.activity_new_question, null);
        Init();




        /**
         * 下面是主要代码：
         */
        draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
//                .setUri(Uri.parse("http://s1.dwstatic.com/group1/M00/9B/31/468f0fc71e49479bf021c64cefee2882.gif"))//路径
                .setUri(Uri.parse("asset://com.baidumap.administrator.happystudy/new_problem.gif"))//路径
                .build();
        dvWelcome = (SimpleDraweeView) findViewById(R.id.dv_welcome);
        dvWelcome.setController(draweeController);

        Api.quizGetSubject(this, sHelper.getString(Constant.TOKEN));


    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        setHeaderBack();
        initTitleRightLayout();
        setHeaderTitle(R.string.xin_de_ti_wen);

    }

    private void initTitleRightLayout() {
        mAbTitleBar.clearRightView();
        View rightViewMore = mInflater.inflate(R.layout.fa_bu_ti_mu, null);
        mAbTitleBar.addRightView(rightViewMore);
        TextView imgAdd = (TextView) rightViewMore.findViewById(R.id.iv_publish);

        imgAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mTitle = getEidtTextValue(etTitle);
                mContent = getEidtTextValue(tvContent);
                mLeiXing = getTextViewValue(tvXuanZeLeiXing);

//                ToastUtil.showMessage(NewQuestionActivity.this, Bimp.tempSelectBitmap.size() + "");


                if (AbStrUtil.isEmpty(mTitle)) {
                    ToastUtil.showMessage(NewQuestionActivity.this, "标题不能为空");
                    return;
                } else if (AbStrUtil.isEmpty(mContent)) {
                    ToastUtil.showMessage(NewQuestionActivity.this, "内容不能为空");
                    return;
                } else if (Bimp.tempSelectBitmap.size() == 0) {
                    ToastUtil.showMessage(NewQuestionActivity.this, "请先添加问题照片");
                    return;
                } else if (AbStrUtil.isEmpty(mLeiXing)) {
                    ToastUtil.showMessage(NewQuestionActivity.this, "请选择类型");
                    return;
                } else if (mLeiXing.equals("选择习题类型")) {
                    ToastUtil.showMessage(NewQuestionActivity.this, "请选择类型");
                    chooseKemu();
                    return;
                }
                File file1 = null;
                File file2 = null;
                File file3 = null;

                int size = Bimp.tempSelectBitmap.size();

                if (size > 0) {
                    switch (size) {
                        case 1:
                            file1 = compressImage(Bimp.tempSelectBitmap.get(0).getBitmap());
                            break;
                        case 2:
                            file2 = compressImage(Bimp.tempSelectBitmap.get(1).getBitmap());

                            break;
                        case 3:
                            file3 = compressImage(Bimp.tempSelectBitmap.get(2).getBitmap());

                            break;
                    }
                }


                LoadingDialogUtil.showGifdialog(NewQuestionActivity.this.getSupportFragmentManager());
                Api.quizAdd(NewQuestionActivity.this, file1, file2, file3, sHelper.getString(Constant.TOKEN), mKemuId, sHelper.getString(Constant.UID), mTitle, mContent);
//                Toast.makeText(NewQuestionActivity.this, "发布成功", Toast.LENGTH_SHORT).show();

                //startActivity(NewQuestionActivity.class);
            }
        });


    }

    private void chooseKemu() {

        StyledDialog.buildBottomSheetLv("选择科目", kemuList, "选择科目", new MyItemDialogListener() {
            @Override
            public void onItemClick(CharSequence text, int position) {
//                ToastUtil.showMessage(QueRenDingDanActivity.this, text + "---" + position);
                tvXuanZeLeiXing.setText(text);
                mKemuId = kemuIdList.get(position);
            }
        }).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_xuanze:
//                setBackgroundAlpha(this, 0.5f);
//                mPopupWindow.showAtLocation(mLlXuanze, Gravity.BOTTOM, 0, 0);
                chooseKemu();
                break;
            case R.id.math:
                tvXuanZeLeiXing.setText("数学");
                mPopupWindow.dismiss();
//                mLlBeforeChoose.setVisibility(View.GONE);
//                mRlAfterChoose.setVisibility(View.VISIBLE);
                break;
            case R.id.english:
                tvXuanZeLeiXing.setText("英语");
                mPopupWindow.dismiss();
//                mLlBeforeChoose.setVisibility(View.GONE);
//                mRlAfterChoose.setVisibility(View.VISIBLE);
                break;
            case R.id.chinese:
                tvXuanZeLeiXing.setText("语文");
                mPopupWindow.dismiss();
//                mLlBeforeChoose.setVisibility(View.GONE);
//                mRlAfterChoose.setVisibility(View.VISIBLE);
                break;
            case R.id.cancel:
                mPopupWindow.dismiss();
                break;
            case R.id.iv_picture://照片选择
                setBackgroundAlpha(this, 0.5f);
                mPhotoPopup.showAtLocation(mIvPicture, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.photo:
                mPhotoPopup.dismiss();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 1);
                break;
            case R.id.picture:
                mPhotoPopup.dismiss();
                Intent intent1 = new Intent(Intent.ACTION_PICK);
                intent1.setType("image/*");
                startActivityForResult(intent1, 2);
                break;
            case R.id.cancel_photo:
                mPhotoPopup.dismiss();
                break;
            case R.id.image:
                Intent intent2 = new Intent(NewQuestionActivity.this, ImageActivity.class);
                startActivity(intent2);
                break;
        }
    }

    public void initPopWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow, null);
        TextView math = (TextView) view.findViewById(R.id.math);
        TextView english = (TextView) view.findViewById(R.id.english);
        TextView chinese = (TextView) view.findViewById(R.id.chinese);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        math.setOnClickListener(this);
        english.setOnClickListener(this);
        chinese.setOnClickListener(this);
        cancel.setOnClickListener(this);
        mPopupWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(123, 133, 234, 134)));
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (NewQuestionActivity.this != null) {
                    setBackgroundAlpha(NewQuestionActivity.this, 1f);
                }
            }
        });
    }

    public void initPhotoPopup() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_photo, null);
        TextView photo = (TextView) view.findViewById(R.id.photo);
        TextView picture = (TextView) view.findViewById(R.id.picture);
        TextView cancelPhoto = (TextView) view.findViewById(R.id.cancel_photo);
        picture.setOnClickListener(this);
        photo.setOnClickListener(this);
        cancelPhoto.setOnClickListener(this);

        mPhotoPopup = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPhotoPopup.setFocusable(true);
        mPhotoPopup.setTouchable(true);
        mPhotoPopup.setBackgroundDrawable(new ColorDrawable(Color.argb(123, 133, 234, 134)));
        mPhotoPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (NewQuestionActivity.this != null) {
                    setBackgroundAlpha(NewQuestionActivity.this, 1f);
                }
            }
        });
    }

    /**
     * 设置页面的透明度
     *
     * @param bgAlpha 1表示不透明
     */
    public void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        if (bgAlpha == 1) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        activity.getWindow().setAttributes(lp);
    }


    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {
        if (url.equals(Constant.QUIZ_ADD) && jo != null) {
            CarDel carDel = new CarDel(jo.toString());
            if (carDel.getCode().equals("200")) {
                ToastUtil.showMessage(this, "发布成功");
                finish();
            } else {
                ToastUtil.showMessage(this, carDel.getMsg());
            }
        }
        if (url.equals(Constant.QUIZ_GET_SUBJECT) && jo != null) {
            Subject m_login = new Subject(jo.toString());


            if (m_login != null) {


                if (m_login.getCode().equals("200")) {
                    kemuList.clear();

                    List<Subject.DataBean> dataBeanList = m_login.getData();

                    for (int i = 0; i < dataBeanList.size(); i++) {
                        kemuList.add(new BottomSheetBean(R.mipmap.ic_launcher, dataBeanList.get(i).getSubject_name()));
                        kemuIdList.add(dataBeanList.get(i).getSubject_id());
                    }

                } else {
                    ToastUtil.showMessage(this, m_login.getMsg());
                }
            }

        }
    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }


    public void Init() {

        pop = new PopupWindow(NewQuestionActivity.this);

        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);

        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
 
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                photo();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
//                ToastUtil.showMessage(NewQuestionActivity.this, "xiangce");
                Intent intent = new Intent(NewQuestionActivity.this,
                        AlbumActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });

        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        adapter.update();
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == Bimp.tempSelectBitmap.size()) {
                    Log.i("ddddddd", "----------");
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(NewQuestionActivity.this, R.anim.activity_translate_in));
                    pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                } else {
                    Intent intent = new Intent(NewQuestionActivity.this,
                            GalleryActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });

    }

    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if (Bimp.tempSelectBitmap.size() == 3) {
                return 3;
            }
            return (Bimp.tempSelectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            GridAdapter.ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new GridAdapter.ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (GridAdapter.ViewHolder) convertView.getTag();
            }

            if (position == Bimp.tempSelectBitmap.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 3) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) { 
                        if (Bimp.max == Bimp.tempSelectBitmap.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }
            }).start();
        }
    }

    public String getString(String s) {
        String path = null;
        if (s == null)
            return "";
        for (int i = s.length() - 1; i > 0; i++) {
            s.charAt(i);
        }
        return path;
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.update();
    }

//    protected void onRestart() {
//
//        super.onRestart();
//    }

    private static final int TAKE_PICTURE = 0x000001;

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.tempSelectBitmap.size() < 3 && resultCode == RESULT_OK) {

                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);

                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    Bimp.tempSelectBitmap.add(takePhoto);

//                    imagesPath.add(getImgStr(bm).replace(" ", ""));
//                    ToastUtil.showMessage(NewQuestionActivity.this, data.getExtras().get("data") + "");
                }
                break;
        }
    }

    /**
     * 将Bitmap转换成Base64
     *
     * @param bit
     * @return
     */
    public String getImgStr(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            for (int i = 0; i < PublicWay.activityList.size(); i++) {
                if (null != PublicWay.activityList.get(i)) {
                    PublicWay.activityList.get(i).finish();
                }
            }
            System.exit(0);
        }
        return true;
    }

    /**
     * 压缩图片（质量压缩）
     *
     * @param image
     */

    public static File compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;

        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
//        long length = baos.toByteArray().length;
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片


        File file = new File(Environment.getExternalStorageDirectory() + "/temp.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return file;
    }
}
